package com.example.webdownloadserver.util;

import org.apache.commons.io.output.FileWriterWithEncoding;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class TxtFileParseUtil {
	
	private static Logger LOGGER = LoggerFactory.getLogger(TxtFileParseUtil.class);
	
	public static List<String> readFile(String filepath) throws IOException {

		InputStreamReader fr = null;  
		BufferedReader br = null;  
		fr = new InputStreamReader(new FileInputStream(filepath),"GBK"); 
		br = new BufferedReader(fr);  
		String rec = null;  // 一行   
		List<String> listFile = new ArrayList<String>();  
		try {  
			// 读取一行   
			while ((rec = br.readLine()) != null) {  
				listFile.add(rec);  
			}  
		} catch (Exception e) {  
			LOGGER.error("解析文件失败",e);
		} finally {  
			if (fr != null) {  
				fr.close();  
			}  
			if (br != null) {  
				br.close();  
			}  
		}  
		return listFile;
	}

	/**
	 * 写入磁盘
	 * @param filepath
	 * @param filename
	 * @param list
	 * @throws IOException
	 */
	public static void writeFile(String filepath,String filename,List<String> list) throws IOException  {
		BufferedWriter bw = null;
		try {  
			if (!new File(filepath).isDirectory()){  
				new File(filepath).mkdirs();   
			}
			bw = new BufferedWriter(new FileWriterWithEncoding(new File(filepath+File.separator+filename),"GBK",true)); // 附加
				for (String string : list) {
					bw.write(string+"\r\n");  
				}
				bw.flush();
		} catch (FileNotFoundException e) {  
			LOGGER.error("writeFile error",e);  
		} catch (IOException e) {  
			LOGGER.error("writeFile error",e);
		} finally {
			if(bw != null) {
				bw.close();  
			}
		}
	}


	/**
	 * 写入oss
	 * @param list
	 * @param fileName
	 * @return
	 * @throws IOException
	 */
	public static String writeFileToOss(List<String> list, String fileName) throws IOException {
		try {
			StringBuffer sb = new StringBuffer();
			for (String s : list) {
				sb.append(s).append("\r\n");
			}
			byte[] bytes = sb.toString().getBytes("UTF-8");
			InputStream inputStream = new ByteArrayInputStream(bytes);
			String time = System.currentTimeMillis()+"";
//			OssUtil.uploadFile2OSS(inputStream, time+fileName, "receipt/common/", null);
			return null;
		}catch (IOException e){
			LOGGER.error("writeFile error",e);
		}
		return null;
	}

}
